package com.citic.topview.app.mobile.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.citic.topview.app.service.UpdateManagerService;
import com.citic.topview.common.app.vo.UpdateManagerVO;
import com.citic.topview.common.vo.AppResultVO;
import com.citic.topview.system.controller.BaseController;

@Controller
@RequestMapping("/app/appUpdateManager")
public class AppUpdateManagerController extends BaseController{

	@Autowired
	private UpdateManagerService updateManagerService;
	
	@ResponseBody
	@RequestMapping("checkUpdate")
	public AppResultVO<Object> checkUpdate(@RequestBody UpdateManagerVO updateManagerVO, HttpServletRequest request, HttpServletResponse response) {
		AppResultVO<Object> resultVO = null;
		
		Map<String, Object> params = new HashMap<>();
		params.put("type", updateManagerVO.getType().equals("ios") ? "0" : "1");
		params.put("status", updateManagerVO.getStatus().equals("dev") ? "0" : "1");
		List<UpdateManagerVO> list = updateManagerService.list(params);
		
		UpdateManagerVO vo = null;
		if (!CollectionUtils.isEmpty(list)) {
			vo = list.get(0);
			int oldCode = Integer.parseInt(updateManagerVO.getVersionCode());
			int newCode = Integer.parseInt(vo.getVersionCode());
			vo.setUpdate(oldCode < newCode);
			
			
			// 手机操作系统的不同，返回的地址也不相同
			if (updateManagerVO.getType().equals("android")) {

			}
			
			if (updateManagerVO.getType().equals("ios")) {
				String url = null;
					try {
						url = URLDecoder.decode(vo.getDownloadUrl(), "utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				vo.setDownloadUrl("app/appUpdateManager/updatePage?url=" + url);
			}
		} 
		
		resultVO = setResult(AppResultVO.SUCCESS, "ok", null);
		resultVO.setBizVO(vo);
		return resultVO;
		
	}
	
	@RequestMapping("updatePage")
	public String download4pad(String url, Model model) {
		model.addAttribute("url", url);
		return "app/updateManager/update";
	}
}
